package com.atguigu.app.dws;

/**
 * ClassName: Dws02TrafficIsNewPageViewWindow
 * Package: com.atguigu.app.dws
 * Description:
 *
 * @Author 周东东
 * @Create 2023/5/20 9:33
 * @Version 1.0
 */
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TrafficPageViewBean;
import com.atguigu.bean.TrafficPageViewisNewewBean;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.KafkaUtil;
import com.atguigu.utils.MyClickHouseUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws02TrafficIsNewPageViewWindow {
    public static void main(String[] args) throws Exception {
    //TODO 1.获取执行环境
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.setParallelism(1);
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

    //TODO 2.读取Kafka DWD层页面日志主题数据
    DataStreamSource<String> kafkaDS = env.fromSource(KafkaUtil.getKafkaSource("dwd_traffic_page_log", "Dws02TrafficIsNewPageViewWindow"),
            WatermarkStrategy.noWatermarks(),
            "kafka-source");

    //TODO 3.将数据转换为JSON对象
    SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

    //TODO 4.按照Mid进行分组
    KeyedStream<JSONObject, String> keyedByMidDS = jsonObjDS.keyBy(json -> json.getJSONObject("common").getString("mid"));

    //TODO 5.去重Mid,并将数据转JavaBean换为对象
    SingleOutputStreamOperator<TrafficPageViewisNewewBean> trafficPageViewByMidDS = keyedByMidDS.map(new RichMapFunction<JSONObject, TrafficPageViewisNewewBean>() {

        private ValueState<String> valueState;

        @Override
        public void open(Configuration parameters) throws Exception {
            ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("mid-state", String.class);

            //设置TTL
            StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1))
                    .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                    .build();
            stateDescriptor.enableTimeToLive(ttlConfig);

            valueState = getRuntimeContext().getState(stateDescriptor);
        }

        @Override
        public TrafficPageViewisNewewBean map(JSONObject value) throws Exception {

            //取出状态数据
            String lastDt = valueState.value();
            long uvCt = 0L;
            long skipCt = 0L;
            String curDt = DateFormatUtil.toDate(value.getLong("ts"));
            if (lastDt == null || !lastDt.equals(curDt)) {
                uvCt = 1L;
                valueState.update(curDt);
            }
            JSONObject page = value.getJSONObject("page");
            if (page != null) {
                String pageId = page.getString("page_id");
                String lastPageId = page.getString("last_page_id");
                if (pageId != null && lastPageId == null) {
                    skipCt = 1L;
                }
            }

            //获取common信息
            JSONObject common = value.getJSONObject("common");

            return new TrafficPageViewisNewewBean("", "",
                    common.getString("is_new"),
                    common.getString("sid"),
                    uvCt,
                    0L,
                    1L,
                    value.getJSONObject("page").getLong("during_time"),
                    skipCt,
                    value.getLong("ts"));
        }
    });
    //TODO 6.按照Sid分组
    KeyedStream<TrafficPageViewisNewewBean, String> keyedBySidDS = trafficPageViewByMidDS.keyBy(TrafficPageViewisNewewBean::getSid);

    //TODO 7.去重Sid
    SingleOutputStreamOperator<TrafficPageViewisNewewBean> trafficPageViewBySidDS = keyedBySidDS.map(new RichMapFunction<TrafficPageViewisNewewBean, TrafficPageViewisNewewBean>() {

        private ValueState<String> valueState;

        @Override
        public void open(Configuration parameters) throws Exception {
            ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("sid-state", String.class);

            StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.hours(1))
                    .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                    .build();
            stateDescriptor.enableTimeToLive(ttlConfig);

            valueState = getRuntimeContext().getState(stateDescriptor);
        }

        @Override
        public TrafficPageViewisNewewBean map(TrafficPageViewisNewewBean value) throws Exception {

            //获取状态数据
            String state = valueState.value();

            if (state == null) {
                value.setSvCt(1L);
                valueState.update("1");
            }

            return value;
        }
    });

    //TODO 8.提取时间戳生成Watermark
    SingleOutputStreamOperator<TrafficPageViewisNewewBean> trafficPageViewWithWMDS = trafficPageViewBySidDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficPageViewisNewewBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<TrafficPageViewisNewewBean>() {
        @Override
        public long extractTimestamp(TrafficPageViewisNewewBean element, long recordTimestamp) {
            return element.getTs();
        }
    }));

    //TODO 9.分组、开窗、聚合
    WindowedStream<TrafficPageViewisNewewBean, String, TimeWindow> windowedStream = trafficPageViewWithWMDS.keyBy(TrafficPageViewisNewewBean::getIsNew).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)));

    SingleOutputStreamOperator<Object> resultDS = windowedStream.reduce(new ReduceFunction<TrafficPageViewisNewewBean>() {
        @Override
        public TrafficPageViewisNewewBean reduce(TrafficPageViewisNewewBean value1, TrafficPageViewisNewewBean value2) throws Exception {
            value1.setUvCt(value1.getUvCt() + value2.getUvCt());
            value1.setPvCt(value1.getPvCt() + value2.getPvCt());
            value1.setSvCt(value1.getSvCt() + value2.getSvCt());
            value1.setDurSum(value1.getDurSum() + value2.getDurSum());
            value1.setSkipCt(value1.getSkipCt() + value2.getSkipCt());
            return value1;
        }
    }, new WindowFunction<TrafficPageViewisNewewBean, Object, String, TimeWindow>() {
        @Override
        public void apply(String key, TimeWindow window, Iterable<TrafficPageViewisNewewBean> input, Collector<Object> out) throws Exception {
            //取出数据
            TrafficPageViewisNewewBean next = input.iterator().next();
            next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
            next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
            next.setTs(System.currentTimeMillis());

            //输出数据
            out.collect(next);
        }
    });
    resultDS.print(">>>>>>>");
    resultDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_is_new_page_view_window values(?,?,?,?,?,?,?,?,?)"));
    env.execute("Dws01TrafficVcChArIsNewPageViewWindow");

}
}

